import React, { useRef, useState } from 'react';
import { PageContainer, ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Modal, Form, Input, Space, AutoComplete } from 'antd';
import { api } from '@/services/api';
import { Tag, TagRequest } from '@/services/generated/models';

const TagList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [editingTag, setEditingTag] = useState<Tag | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [autoCompleteOptions, setAutoCompleteOptions] = useState<{ value: string }[]>([]);

  const handleSubmit = async (values: TagRequest) => {
    try {
      if (editingTag) {
        await api.navigation.navigationTagsUpdate({
          id: editingTag.id,
          tagRequest: values,
        });
        message.success('更新成功');
      } else {
        await api.navigation.navigationTagsCreate({
          tagRequest: values,
        });
        message.success('创建成功');
      }
      setModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleBatchDelete = async () => {
    if (!selectedRowKeys.length) {
      message.warning('请选择要删除的标签');
      return;
    }
    try {
      await Promise.all(
        selectedRowKeys.map((id) =>
          api.navigation.navigationTagsDestroy({
            id: id as number,
          })
        )
      );
      message.success('批量删除成功');
      setSelectedRowKeys([]);
      actionRef.current?.reload();
    } catch (error) {
      message.error('批量删除失败');
    }
  };

  const handleSearch = async (searchText: string) => {
    if (!searchText) {
      setAutoCompleteOptions([]);
      return;
    }
    try {
      const response = await api.navigation.navigationTagsList({
        name: searchText,
      });
      const options = response
        .filter(tag => tag.name.toLowerCase().includes(searchText.toLowerCase()))
        .map(tag => ({
          value: tag.name,
        }));
      setAutoCompleteOptions(options);
    } catch (error) {
      console.error('获取标签建议失败:', error);
    }
  };

  const columns: ProColumns<Tag>[] = [
    {
      title: '标签名称',
      dataIndex: 'name',
      copyable: true,
      ellipsis: true,
      width: 200,
    },
    {
      title: '描述',
      dataIndex: 'description',
      ellipsis: true,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      width: 160,
      search: false,
    },
    {
      title: '创建者',
      dataIndex: 'created_by',
      width: 100,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 180,
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          onClick={() => {
            setEditingTag(record);
            form.setFieldsValue(record);
            setModalVisible(true);
          }}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="link"
          danger
          onClick={async () => {
            try {
              await api.navigation.navigationTagsDestroy({
                id: record.id,
              });
              message.success('删除成功');
              actionRef.current?.reload();
            } catch (error) {
              message.error('删除失败');
            }
          }}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<Tag>
        headerTitle="标签列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        toolBarRender={() => [
          <Space key="buttons">
            <Button
              type="primary"
              onClick={() => {
                setEditingTag(null);
                form.resetFields();
                setModalVisible(true);
              }}
            >
              新建标签
            </Button>
            <Button danger onClick={handleBatchDelete} disabled={!selectedRowKeys.length}>
              批量删除
            </Button>
          </Space>,
        ]}
        request={async (params) => {
          try {
            const response = await api.navigation.navigationTagsList({
              name: params.name,
            });
            return {
              data: response || [],
              success: true,
              total: response?.length || 0,
            };
          } catch (error) {
            message.error('获取数据失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
      />

      <Modal
        title={editingTag ? '编辑标签' : '新建标签'}
        visible={modalVisible}
        onOk={() => form.submit()}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="标签名称"
            rules={[{ required: true, message: '请输入标签名称' }]}
          >
            <AutoComplete
              options={autoCompleteOptions}
              onSearch={handleSearch}
              placeholder="输入标签名称"
              filterOption={(inputValue, option) =>
                option!.value.toLowerCase().indexOf(inputValue.toLowerCase()) !== -1
              }
            />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default TagList;
